
#ifndef GRIDMAP
#define GRIDMAP

#include "grid.h"
#include "position.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <map>
#include <fstream>

using namespace std;

class Gridmap {

	public:
	
	map < Position, Grid* > posmap;
	
	Grid start;
	Grid* current;
	
	fstream output;

	public:
	
	Gridmap();
	~Gridmap();
	
	void close_output() {
	  output.close();
	}

	Position* current_position() const;
	const bool move( int direction );
	const int inv(int direction) {
		if ( direction == NORTH ) return SOUTH;
		else if ( direction == SOUTH ) return NORTH;
		else if ( direction == EAST) return WEST;
		else return EAST;
	}
	
};

Gridmap::Gridmap() : start(0,0), output( "map.txt", fstream::in | fstream::out ) {
	start.set_start();
	current = &start;
	posmap[ start.get_position() ] = &start;
}

Gridmap::~Gridmap() {}

Position* Gridmap::current_position() const {
  Position p = (*current).get_position();
  Position* np = new Position( p.x, p.y );
  return np;
}

const bool Gridmap::move( int direction ) {
	
	Position p = (*current).get_position().adjacent_pos(direction);
	
	// Grid already exists
	if ( posmap.count( p ) > 0 ) {		
		
		(*current).leave();
		
		(*current).add_grid( direction, posmap[p] );
		current = posmap[p];

		(*current).enter();

		Log::Write( "current grid: (%d, %d)", (*current).get_x(), (*current).get_y()  );
		output << "current grid: (";
		output << (*current).get_x();
		output << ", ";
		output << (*current).get_y();
		output << ")\n";

		return true;
	}
	else { //Grid does not exist
	
		(*current).leave();
	
		Grid& g = (*current).add_grid( direction );
		posmap[p] = &g;
		current = &g;
		
		(*current).enter();

		Log::Write( "current grid: (%d, %d)", (*current).get_x(), (*current).get_y()  );
		output << "current grid: (";
		output << (*current).get_x();
		output << ", ";
		output << (*current).get_y();
		output << ")\n";

		return false;
	}
	
}

#endif
